package net.oschina.app.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.oschina.app.R;
import net.oschina.app.bean.Comment;
import net.oschina.app.bean.CommentList;
import net.oschina.app.bean.Tweet;
import net.oschina.app.bean.User;
import net.oschina.app.emoji.InputHelper;
import net.oschina.app.ui.adapter.TweetDetailAdapter;
import net.oschina.app.ui.view.CircleImageView;
import net.oschina.app.ui.widget.MyLinkMovementMethod;
import net.oschina.app.ui.widget.MyURLSpan;
import net.oschina.app.ui.widget.TweetTextView;
import net.oschina.app.util.KJAnimations;
import net.oschina.app.util.StringUtils;
import net.oschina.app.util.TypefaceUtils;
import net.oschina.app.util.XmlUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by CXB on 2017/4/2.
 * 实现动弹页面的跳转
 * 动弹详情的优化
 */

public class TweetDetailActivity extends AppCompatActivity {
    @BindView(R.id.tweetdetail_toolbar)
    Toolbar mTweetdetailToolbar;
    @BindView(R.id.iv_tweet_face)
    CircleImageView mIvTweetFace;
    @BindView(R.id.tv_tweet_name)
    TextView mTvTweetName;
    @BindView(R.id.tweet_item)
    TweetTextView mTweetItem;
    @BindView(R.id.iv_tweet_image)
    ImageView mIvTweetImage;
    @BindView(R.id.tv_likeusers)
    TextView mTvLikeusers;
    @BindView(R.id.tv_tweet_time)
    TextView mTvTweetTime;
    @BindView(R.id.tv_tweet_platform)
    TextView mTvTweetPlatform;
    @BindView(R.id.tv_del)
    TextView mTvDel;
    @BindView(R.id.tv_like_state)
    TextView mTvLikeState;
    @BindView(R.id.item_commont)
    ImageView mItemCommont;
    @BindView(R.id.tv_tweet_comment_count)
    TextView mTvTweetCommentCount;
    @BindView(R.id.ll_info)
    RelativeLayout mLlInfo;
    @BindView(R.id.ll_tweetdetail_item)
    LinearLayout mLlTweetdetailItem;
    @BindView(R.id.tv_comment_count)
    TextView mTvCommentCount;
    @BindView(R.id.et_input)
    EditText mEtInput;
    @BindView(R.id.ib_emoji)
    ImageButton mIbEmoji;
    @BindView(R.id.ib_biz_chat)
    ImageButton mIbBizChat;
    @BindView(R.id.ll_tweetdetail)
    RelativeLayout mLlTweetdetail;
    @BindView(R.id.tweet_detail_xrl)
    XRecyclerView mTweetDetailXrl;
    private Tweet mTweet;
    private CommentList commentLists;
    private List<Comment> commentList;
    private TweetDetailAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tweetdetail_activity);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.tweetdetail_toolbar);
        setSupportActionBar(toolbar);
        //关键下面两句话，设置了回退按钮，及点击事件的效果
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        List<Tweet> list = (List<Tweet>) getIntent().getSerializableExtra("mTweets");
        int position = getIntent().getIntExtra("position", -1) - 1;
        mTweet = list.get(position);
        refreshHolderView(mTweet);

        //设置评论
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mTweetDetailXrl.setLayoutManager(layoutManager);
        //获取数据
        initData();
    }

    //获取评论数据 catalog3id6065855page0.xml
    private void initData() {
        int id = mTweet.getId();
       String url = "http://10.0.2.2:8080/oschina/commentlist/catalog3id6066102page0.xml";
       // String url = "http://10.0.2.2:8080/oschina/commentlist/catalog3id6066159page0.xml";
        OkHttpClient Client = new OkHttpClient();
        Request requst = new Request.Builder().url(url).build();
        Call call = Client.newCall(requst);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                commentLists = XmlUtils.toBean(CommentList.class, inputStream);
                if (commentLists != null) {
                    commentList = commentLists.getCommentlist();

                }
                TweetDetailActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (commentList != null) {
                            adapter = new TweetDetailAdapter(TweetDetailActivity.this, commentList);
                            mTweetDetailXrl.setAdapter(adapter);
                        }
                    }
                });
            }
        });
    }
    //富文本设置
    public void refreshHolderView(final Tweet tweet) {
        Glide.with(this).load(tweet.getPortrait()).into(mIvTweetFace);
        mTvDel.setVisibility(View.GONE);
        mTvTweetName.setText(tweet.getAuthor());//作者
        mTvTweetTime.setText(StringUtils.friendly_time(tweet.getPubDate()));
        //内容
        mTweetItem.setMovementMethod(MyLinkMovementMethod.a());
        mTweetItem.setFocusable(false);
        mTweetItem.setLongClickable(false);

        Spanned span = Html.fromHtml(tweet.getBody().trim());

        if (!StringUtils.isEmpty(tweet.getAttach())) {

            SpannableString str = new SpannableString("c");
            mTweetItem.setText(str);
            span = InputHelper.displayEmoji(getResources(), span);
            mTweetItem.append(span);
        } else {
            span = InputHelper.displayEmoji(getResources(), span);
            mTweetItem.setText(span);
        }
        MyURLSpan.parseLinkText(mTweetItem, span);

        //评论条数
        mTvTweetCommentCount.setText(tweet.getCommentCount() + "");
     /*   if (tweet.getLikeUser() == null) {
            mTvLikeusers.setVisibility(View.GONE);
        }*/
        //设置点赞效果
        setLikeUsers(tweet, this, mTvLikeusers, true);

        //设置点赞的字体图标
        TypefaceUtils.setTypeface(this, mTvLikeState);

        if (tweet.getLikeUser() == null) {
            mTvLikeState.setVisibility(View.GONE);
        } else {
            mTvLikeState.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateLikeState(tweet);
                }
            });
        }

        if (tweet.getIsLike() == 1) {
            mTvLikeState.setTextColor(getResources().getColor(R.color.day_colorPrimary));
        } else {
            mTvLikeState.setTextColor(getResources().getColor(R.color.gray));
        }
    }

    private void updateLikeState(Tweet tweet) {
        User user = new User();
        user.setName("billy");
        user.setId(10001);

        if (tweet.getIsLike() == 1) {
            tweet.setIsLike(0);
            tweet.setLikeCount(tweet.getLikeCount() - 1);
            if (!tweet.getLikeUser().isEmpty()) {
                tweet.getLikeUser().remove(0);
            }
            mTvLikeState.setTextColor(getResources().getColor(R.color
                    .gray));
        } else {
            mTvLikeState.setAnimation(KJAnimations.getScaleAnimation(1.5f, 300));
            mTvLikeState.setTextColor(getResources().getColor(R.color
                    .day_colorPrimary));
            tweet.setIsLike(1);
            tweet.setLikeCount(tweet.getLikeCount() + 1);
            tweet.getLikeUser().add(0, user);
        }
        setLikeUsers(tweet, this, mTvLikeusers, true);
    }

    /**
     * 处理点赞
     *
     * @param tweet
     * @param context
     * @param tvLikeusers
     * @param limit
     */
    private void setLikeUsers(Tweet tweet, Context context, TextView tvLikeusers, boolean limit) {
        // 构造多个超链接的html, 通过选中的位置来获取用户名
        if (tweet.getLikeCount() > 0 && tweet.getLikeUser() != null && !tweet.getLikeUser().isEmpty()) {
            tvLikeusers.setVisibility(View.VISIBLE);
            tvLikeusers.setMovementMethod(LinkMovementMethod.getInstance());
            tvLikeusers.setFocusable(false);
            tvLikeusers.setLongClickable(false);
            tvLikeusers.setText(addClickablePart(tweet, context, limit), TextView.BufferType.SPANNABLE);
        } else {
            tvLikeusers.setVisibility(View.GONE);
            tvLikeusers.setText("");
        }
    }

    /**
     * @return
     */
    private SpannableStringBuilder addClickablePart(Tweet tweet, final Context context, boolean limit) {

        StringBuilder sbBuilder = new StringBuilder();
        int showCunt = tweet.getLikeUser().size();
        if (limit && showCunt > 4) {//最多显示4个
            showCunt = 4;
        }

        for (int i = 0; i < showCunt; i++) {
            sbBuilder.append(tweet.getLikeUser().get(i).getName() + "、");
        }

        String likeUsersStr = sbBuilder.substring(0, sbBuilder.lastIndexOf("、")).toString();

        SpannableString spanStr = new SpannableString("");
        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(likeUsersStr);

        String[] likeUsers = likeUsersStr.split("、");

        if (likeUsers.length > 0) {
            // 最后一个
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = likeUsersStr.indexOf(name) + spanStr.length();
                final int index = i;
                ssb.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        // ds.setColor(R.color.link_color); // 设置文本颜色
                        // 去掉下划线
                        ds.setUnderlineText(false);
                    }

                }, start, start + name.length(), 0);
            }
        }
        if (likeUsers.length < tweet.getLikeCount()) {
            ssb.append("等");
            int start = ssb.length();
            String more = tweet.getLikeCount() + "人";
            ssb.append(more);
            ssb.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    // ds.setColor(R.color.link_color); // 设置文本颜色
                    // 去掉下划线
                    ds.setUnderlineText(false);
                }

            }, start, start + more.length(), 0);
            return ssb.append("觉得很赞");
        } else {
            return ssb.append("觉得很赞");
        }
    }
}
